#!/usr/bin/env python
# @FileName :user.py
# @Time :2025/8/28 19:17
# @Author :chenjiajun
from wtforms import Form, StringField
from wtforms.validators import DataRequired,Email,Regexp,ValidationError
from werkzeug.security import check_password_hash
from model.user import User


class RegisterForm(Form):
    user_account = StringField(validators=[DataRequired()])
    password = StringField(validators=[DataRequired(), Regexp(r'\w{6,18}', message='密码不符合要求')])

    def validate_user_account(self, field):
        if User.query.filter_by(user_account=field.data).first():
            raise ValidationError('用户名已经存在')



class Login(Form):
    username = StringField('user_account',validators=[DataRequired()])
    password = StringField('user_password',validators=[DataRequired()])

    def validate(self):
        super(Login,self).validate()
        if self.errors:
            return False

        user = User.query.filter_by(user_account=self.username.data).first()
        if user and check_password_hash(user.user_password, self.password.data):
            return user
        else:
            raise ValidationError('用户名或密码错误')